package com.weixin.paleituo.activity;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.ClassifyPagerAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.ClassifyBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.ForbidScrollViewpager;
import com.weixin.paleituo.view.LoadingPager;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * Author yichao
 * Time  2017/11/30 9:10
 * Dest 分类商品
 */

public class ClassifyGoodsActivity extends BaseActivity {
    @BindView(R.id.iv_cart_classify_fragment)
    ImageView mIvCartClassifyFragment;
    @BindView(R.id.rl_search_root_classify_fragment)
    RelativeLayout mRlSearchRootClassifyFragment;
    @BindView(R.id.ll_headroot_classify_fragment)
    LinearLayout mLlHeadrootClassifyFragment;
    @BindView(R.id.tl_tab_classify_fragment)
    TabLayout mTlTabClassifyFragment;
    @BindView(R.id.forbidscroll_viewpager_classify_fragment)
    ForbidScrollViewpager mForbidscrollViewpagerClassifyFragment;
    /*    @BindView(R.id.yrecycleview_menu_classify_fragment)
        YRecycleview mYrecycleviewMenuClassifyFragment;
        @BindView(R.id.yrecycleview_content_classify_fragment)
        YRecycleview mYrecycleviewContentClassifyFragment;*/
    private LoadingPager mLoadingPager;
    private int mIntExtra;
    /*    List<ClassifyBean> mMenuClassBeanList=new ArrayList<>();
    List<ChildrenBeanX> mContentChildrenBeanList=new ArrayList<>();
    private ClassifyMenuRecyclerViewAdapter mClassifyMenuRecyclerViewAdapter;
    private ClassifyContentRecyclerViewAdapter mClassifyContentRecyclerViewAdapter;
    private Dialog mLoadingDialog;*/



    @Override
    public void initView() {

        mLoadingPager = new LoadingPager(this) {
            @Override
            protected void close() {
                finish();

            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(ClassifyGoodsActivity.this, R.layout.classify_activity);
            }

            @Override
            protected void reLoading() {
                retry();

            }
        };

     //   UIUtils.inflate(mContext, R.layout.classify_fragment);

        setContentView(mLoadingPager);
    }
    /**
     * 重新加载
     */
    private void retry() {
        Observable<StatusCode<List<ClassifyBean>>> goodsClassifyObservable = ApiUtils.getApi().getGoodsClassify(Contans.defaultToken, BaseApplication.getUserId());
        HttpUtil.getInstance().toSubscribe(goodsClassifyObservable, new ProgressSubscriber<List<ClassifyBean>>(this) {
            @Override
            protected void _onNext(StatusCode<List<ClassifyBean>> listStatusCode) {
                List<ClassifyBean> data = listStatusCode.getData();
                if (listStatusCode.isFlag()&&data!=null&&data.size()>0){
                    mLoadingPager.showPagerView(Contans.STATE_SUCCEED);


                    setClassData(data);


                }else {
                    mLoadingPager.showPagerView(Contans.STATE_EMPTY);
                }


            }

            @Override
            protected void _onError(String message) {

                mLoadingPager.showPagerView(Contans.STATE_ERROR);

            }
        },"",lifecycleSubject,false,true);


/*        Observable<StatusCode<List<ChildrenBeanX>>> categoryObservable= ApiUtils.getApi().getGoodsClassify(Contans.defaultToken)
                .flatMap(new Function<StatusCode<List<ClassifyBean>>, ObservableSource<StatusCode<List<ChildrenBeanX>>>>() {
                    @Override
                    public ObservableSource<StatusCode<List<ChildrenBeanX>>> apply(StatusCode<List<ClassifyBean>> listStatusCode) throws Exception {
                        List<ClassifyBean> classifyBeans = listStatusCode.getData();
                        if (classifyBeans!=null &&classifyBeans.size()>0){
                            int id = classifyBeans.get(0).getId();
                            mMenuClassBeanList.clear();
                            mMenuClassBeanList.addAll(classifyBeans);
                        return  ApiUtils.getApi().getCategoryDetails(id+"");
                        }else {
                            return Observable.error(new ApiException("获取商品分类失败"));
                        }
                    }
                });
        HttpUtil.getInstance().toSubscribe(categoryObservable, new ProgressSubscriber<List<ChildrenBeanX>>(this) {
            @Override
            protected void _onNext(StatusCode<List<ChildrenBeanX>> listStatusCode) {

                List<ChildrenBeanX> childrenBeans = listStatusCode.getData();
                if (listStatusCode.isFlag()&&childrenBeans!=null &&childrenBeans.size()>0){
                    mLoadingPager.showPagerView(Contans.STATE_SUCCEED);
                    mClassifyMenuRecyclerViewAdapter.notifyDataSetChanged();

                        mContentChildrenBeanList.clear();
                        mContentChildrenBeanList.addAll(childrenBeans);
                        mClassifyContentRecyclerViewAdapter.notifyDataSetChanged();

                }else {
                    ToastUtils.makeText(listStatusCode.getDetailMsg());
                    mLoadingPager.showPagerView(Contans.STATE_EMPTY);
                }


            }

            @Override
            protected void _onError(String message) {
                mLoadingPager.showPagerView(Contans.STATE_ERROR);
                ToastUtils.makeText(message+"");

            }
        },"",lifecycleSubject,false,true);*/
    }

    /**
     * 设置分类信息
     * @param data
     */
    private void setClassData(List<ClassifyBean> data) {
        ClassifyPagerAdapter classifyPagerAdapter=new ClassifyPagerAdapter(getSupportFragmentManager(),data);
        //将ViewPager关联到TabLayout上
     //   mForbidscrollViewpagerClassifyFragment.setOffscreenPageLimit(data.size());
        mForbidscrollViewpagerClassifyFragment.setAdapter(classifyPagerAdapter);
        mTlTabClassifyFragment.setupWithViewPager(mForbidscrollViewpagerClassifyFragment);

        mTlTabClassifyFragment.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //切换ViewPager
                mForbidscrollViewpagerClassifyFragment.setCurrentItem(tab.getPosition(),false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        if (mIntExtra ==0){
            mForbidscrollViewpagerClassifyFragment.setCurrentItem(0,false);

        }else if (mIntExtra ==1){

            mForbidscrollViewpagerClassifyFragment.setCurrentItem(1,false);
        }else if (mIntExtra ==2){
            mForbidscrollViewpagerClassifyFragment.setCurrentItem(2,false);

        }else if (mIntExtra==3){
            mForbidscrollViewpagerClassifyFragment.setCurrentItem(3,false);

        }
        mTlTabClassifyFragment.getTabAt(mIntExtra).select();

    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        mIntExtra = intent.getIntExtra(Contans.INTENT_DATA, 0);

        

/*

 */
/*       if (Build.VERSION.SDK_INT >= 21) {
            mLlHeadrootClassifyFragment.setPadding(0,UIUtils.dip2px(20),0,0);
            mLlHeadrootClassifyFragment.setBackgroundColor(Color.parseColor("#1678DA"));

        }else {

        }*//*

        mLlHeadrootClassifyFragment.setPadding(0,0,0,0);
        mMenuClassBeanList.clear();
        mClassifyMenuRecyclerViewAdapter = new ClassifyMenuRecyclerViewAdapter(this,mMenuClassBeanList);
        //设置布局管理器
        mYrecycleviewMenuClassifyFragment.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mYrecycleviewMenuClassifyFragment.setAdapter(mClassifyMenuRecyclerViewAdapter);
        //设置Item增加、移除动画
        mYrecycleviewMenuClassifyFragment.setItemAnimator(new DefaultItemAnimator());
     */
/*   //添加分割线
        mYrecycleviewMenuClassifyFragment.addItemDecoration(new DividerItemDecoration(
                mContext, DividerItemDecoration.VERTICAL));*//*

        mYrecycleviewMenuClassifyFragment.setLoadMoreEnabled(false);
        mYrecycleviewMenuClassifyFragment.setReFreshEnabled(false);
        mClassifyMenuRecyclerViewAdapter.setOnItemClickListener(new ClassifyMenuRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(View v, int position, String categoryId) {
                mClassifyMenuRecyclerViewAdapter.setCheckPostion(position);
                mClassifyMenuRecyclerViewAdapter.notifyDataSetChanged();
             ///   List<ChildrenBean> children = mMenuClassBeanList.get(position).getChildren();
                Observable observable = ApiUtils.getApi().getCategoryDetails(categoryId).compose(RxHelper.getObservaleTransformer())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {

                                if (mLoadingDialog == null) {
                                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(ClassifyGoodsActivity.this, "");
                                }
                                mLoadingDialog.show();
                            }
                        }).subscribeOn(AndroidSchedulers.mainThread());
                HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<ChildrenBeanX>>(ClassifyGoodsActivity.this) {
                    @Override
                    protected void _onNext(StatusCode<List<ChildrenBeanX>> listStatusCode) {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        List<ChildrenBeanX> children = listStatusCode.getData();
                        if (children!=null &&children.size()>0){
                            mContentChildrenBeanList.clear();
                            mContentChildrenBeanList.addAll(children);
                            mClassifyContentRecyclerViewAdapter.notifyDataSetChanged();

                        }else {
                            ToastUtils.makeText(listStatusCode.getDetailMsg());
                            mContentChildrenBeanList.clear();
                            mClassifyContentRecyclerViewAdapter.notifyDataSetChanged();

                        }

                    }

                    @Override
                    protected void _onError(String message) {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        ToastUtils.makeText(message);



                    }
                },"",lifecycleSubject,false,true);



            }
        });

        mClassifyContentRecyclerViewAdapter = new ClassifyContentRecyclerViewAdapter(this,mContentChildrenBeanList);
        //设置布局管理器
        mYrecycleviewContentClassifyFragment.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mYrecycleviewContentClassifyFragment.setAdapter(mClassifyContentRecyclerViewAdapter);
        //设置Item增加、移除动画
        mYrecycleviewContentClassifyFragment.setItemAnimator(new DefaultItemAnimator());
        mYrecycleviewContentClassifyFragment.setLoadMoreEnabled(false);
        mYrecycleviewContentClassifyFragment.setReFreshEnabled(false);
*/

        retry();
    }

    @OnClick(R.id.iv_cart_classify_fragment)
    public void onMIvCartClassifyFragmentClicked() {

        ShopCarActivity.startActivity(this);

    }

    @OnClick(R.id.rl_search_root_classify_fragment)
    public void onMRlSearchRootClassifyFragmentClicked() {

        SearchGoodsActivity.startActivity(this);
    }

    public static void startActivity(Context context ,int  postion)  {
        Intent intent = new Intent(context, ClassifyGoodsActivity.class);

        intent.putExtra(Contans.INTENT_DATA,postion);
        context.startActivity(intent);
    }

    @OnClick(R.id.iv_back_activity_classify_fragment)
    public void onBack() {
        finish();
    }
}
